#include "TcpServer.h"
#include "ThreadPool.h"

ThreadPool *gPool = nullptr;

class MyTask{
public:
    MyTask(const string & msg,const TcpConnectionPtr &con)
    :m_msg(msg),m_con(con){}

    ~MyTask(){}

    void process(){
        m_msg = "msg = " + m_msg;
        //给发送的消息增加“msg = ”就是本次的任务
        //这个任务可以换成更加复杂的任务
        m_con->sendInLoop(m_msg);
    }
private:
    string m_msg;
    TcpConnectionPtr m_con;
};

void onNewConnection(const TcpConnectionPtr &con){
    cout<<"建立连接，连接信息为："<<con->streamToString()<<endl;
}

// void onMessage(const TcpConnectionPtr &con){
//     cout<<"收到消息，连接信息为："<<con->streamToString()<<endl;
//     string msg = con->receive();
//     cout<<"消息内容："<<msg<<endl;
//     con->send("hello handsome\n");
// }

void onMessage(const TcpConnectionPtr &con){
    cout<<"收到消息，连接信息为："<<con->streamToString()<<endl;
    string msg = con->receive();
    cout<<"消息内容："<<msg<<endl;
    
    MyTask task(msg,con);
    gPool->addTask(std::bind(&MyTask::process,task));
}

void onClose(const TcpConnectionPtr &con){
    cout<<"关闭连接，连接信息为："<<con->streamToString()<<endl;
}

int main(){
    // Acceptor acc("192.168.2.57",12345);
    // acc.ready();
    // EventLoop eloop(acc);
    // eloop.setNewConnectionCallback(onNewConnection);
    // eloop.setMessageCallback(onMessage);
    // eloop.setCloseCallback(onClose);
    // eloop.loop();

    // TcpServer ts("192.168.2.57",12345);
    // ts.setAllCallback(onNewConnection,onMessage,onClose);
    // ts.start();
    // return 0;

    ThreadPool pool(4,10);
    pool.start();
    gPool = &pool;
    TcpServer server("192.168.2.57",12345);
    server.setAllCallback(onNewConnection,onMessage,onClose);
    server.start();
    return 0;
}